﻿namespace CommunicationDemo
{
    using System;
    using System.Diagnostics;
    using System.Reactive.Linq;
    using Microsoft.Phone.Controls;
    using Resources;
    using WP7Contrib.Communications;

    public partial class MainPage : PhoneApplicationPage
    {
        private IHandleResources weatherResource;

        private IProviderWeather weatherService;

        // Constructor
        public MainPage()
        {
            weatherResource = new ResourceClient()
                .ForType(ResourceType.Xml)
                .UseUrlForGet("http://www.google.com/ig/api?weather={0}");

            weatherService = new WeatherService(new ResourceClientFactory());

            InitializeComponent();
        }

        private void button1_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            this.weatherResource.Get<xml_api_reply>(location.Text)
                .ObserveOnDispatcher()
                .Subscribe(result =>
                            {
                                var text = string.Format("Current Temp. (Celsius) in {0}: {1}",
                                                        location.Text,
                                                        result.weather[0].current_conditions[0].temp_c[0].data);
                                currentTemperatureCelsius.Text = text;
                            },  
                            exn => Debug.WriteLine("Failed, exception - " + exn.Message),
                            () => Debug.WriteLine("Completed!"));
        }

        private void button2_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            weatherService.Get(location.Text)
                .ObserveOnDispatcher()
                .Subscribe(weather =>
                               {
                                   var text = string.Format("Current Temp. (Celsius) in {0}: {1}",
                                                            location.Text,
                                                            weather.Current.Temperature);
                                   currentTemperatureCelsius.Text = text;
                               },
                               exn => Debug.WriteLine("Failed, exception - " + exn.Message),
                               () => Debug.WriteLine("Completed!"));
        }
    }
}